package com.hivekion.common.reflection;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ReflectionUtils {

    /**
     * 通过字段名从对象或对象的父类中得到字段的值
     * @param object 对象实例
     * @param fieldName 字段名
     * @return 字段对应的值
     * @throws Exception
     */
    public static Object getValue(Object object, String fieldName){
        if (object == null) {
            return null;
        }
        if (StringUtils.isBlank(fieldName)) {
            return null;
        }
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                if (field.getGenericType() != null) {
                    String type = field.getGenericType().toString();
                    if (type.contains("class java.util.Date")) {
                        if (field.get(object) != null) {
                            return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date(field.get(object).toString()));
                        } else {
                            return "";
                        }
                    } else {
                        return field.get(object);
                    }
                }else {
                    return "";
                }
            } catch (Exception e) {
                return "";
            }
        }
        return "";
    }
}
